'use strict';
/**
 * 负责基础表单的增删改查
 */
const Controller = require('egg').Controller;
const Result = require('../../utils/result')
const getUUID = require('../../utils/uuid')
class CommonController extends Controller {
  /**
  * @desc: 路由处理 
  * @param {*} 
  * @return {*}
  */
  async dispatch() {
    const tables = { 'user': { table: 'sys_user' } }
    if (!tables[this.ctx.params.table]) {
      throw new Error('404 访问不存在')
    }
    let method = this.ctx.request.method.toLocaleLowerCase()
    if (this.ctx.params.id && method === 'get') {
      method = 'detail'
    }
    return await this[method](tables[this.ctx.params.table], this.ctx.params)
  }
  /**
   * 获取所有数据
   * @param {Object} tableInfo 
   */
  async get(tableInfo) {
    const { ctx, app } = this;
    const result = await app.mysql.select(tableInfo.table)
    ctx.body = Result.OK(result)
  }
  async detail(tableInfo, { id }) {
    const { ctx, app } = this;
    const result = await app.mysql.get(tableInfo.table, { id })
    ctx.body = Result.OK(result)
  }
  /**
   * 添加数据
   * @param {Object} tableInfo 
   */
  async post(tableInfo) {
    const { ctx,app } = this;
    const data = ctx.request.body
    data['id'] = getUUID()
    data['create_time'] = new Date();
    const result = await app.mysql.insert(tableInfo.table, data)
    ctx.body = Result.OK(result)
  }
  async put(tableInfo, { id }) {
    const { ctx, app } = this;
    let data = ctx.request.body;
    data['id'] = id
    const result = await app.mysql.update(tableInfo.table, data)
    ctx.body = Result.OK(result)
  }
  async delete(tableInfo, { id }) {
    const { ctx, app } = this;
    const result = await app.mysql.delete(tableInfo.table, { id })
    ctx.body = Result.OK(result)
  }
}


module.exports = CommonController;